package com.jiang.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jiang.validate.ValidateUtils;

public class MyInterceptor implements HandlerInterceptor {

	private static Logger logger = null;

	static {
		logger = Logger.getLogger(MyInterceptor.class);
	}

	// 前
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("前置拦截:" + handler.getClass()); // 其实handler就是HandlerMethod类型
		HandlerMethod hm = (HandlerMethod) handler;
		// 调用验证方法
		Map<String,Object> errors = ValidateUtils.validate(hm, request);
		// 如果有错误输出错误并且跳转页面显示，如果没有错误验证通过
		if(errors.size()>0) {
			// 遍历显示所有的错误
			for(Map.Entry<String, Object> entry: errors.entrySet()) {
				System.out.println(entry.getKey()+":" + entry.getValue());
				// 跳转页面略
			}
			return false;
		}
		return true;
	}

	// 中
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.info("中期拦截:" + handler.getClass() + "," + modelAndView);
	}

	// 后
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.info("后期拦截:" + handler.getClass() + "," + ex);
	}

}
